/**
 * 本地缓存
 * LStorage
 * sStorage
 */
import * as Base64Tool from 'base-64';
enum StorageType {
  l = 'localStorage',
  s = 'sessionStorage'
}

interface StorageItem {
  account: string
  password: string
  expires?: string
}

class MyStorage {
  storage: Storage
  constructor(type: StorageType) {
    this.storage = type === StorageType.l ? window.localStorage : window.sessionStorage
  }
  set(
    key: string,
    value: StorageItem,
    expires: boolean | number = false,
  ) {
    if (expires) {
      // 默认设置过期时间为1年，这个可以根据实际情况进行调整
      expires =
        new Date().getTime() +
        (expires === true ? 1000 * 60 * 60 * 24 * 365 : expires * 1000)
    }
    // 对密码加密W
    value.password = Base64Tool.encode(value.password)
    // 存储前先获取
    const arr = this.getStore('loginUserInfo')
    // 存在相同的值就更新，不同就添加
    const res = isExit(arr, value.account)
    if (res !== -1) {
      arr[res] = { ...value, expires }
    } else {
      arr.push({ ...value, expires })
    }
    const data = JSON.stringify(arr)
    this.storage.setItem(key, data)
  }
  private getStore(key: string) {
    const value = this.storage.getItem(key)
    if (value) {
      const data = JSON.parse(value)
      data.forEach((item: { expires: number, account: string }, index: any) => {
        if (item.expires) {
          const now = new Date().getTime()
          if (item.expires && now > item.expires) {
            data.splice(index, 1)
            this.storage.setItem('loginUserInfo', JSON.stringify(data))
          }
        }
      });
      return JSON.parse(value)
    }
    return []
  }
  get(account: string) {
    const arr = this.getStore('loginUserInfo')
    const res = isExit(arr, account)
    if (res !== -1) {
      arr[res].password = Base64Tool.decode(arr[res].password)
      return arr[res]
    }
    return ''
  }
  remove(account: string) {
    const arr = this.getStore('loginUserInfo')
    if (arr) {
      arr.forEach((item: { account: string }, index: any) => {
        if (item.account == account) {
          arr.splice(index, 1)
        }
      });
      this.storage.setItem('loginUserInfo', JSON.stringify(arr))
    }
  }
  clear() {
    this.storage.clear()
  }
}
const isExit = (arr: Array<StorageItem>, account: string): number => {
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    if (item?.account == account) {
      return i
    }
  }
  return -1
}

const LStorage = new MyStorage(StorageType.l)
const SStorage = new MyStorage(StorageType.s)

export {
  LStorage,
  SStorage,

}

